package com.gqr.flowcontrol.countdownlatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Copyright (C), 2020-2024,gqr
 * FileName:CountDownLatchDemo1
 * author:guqingrong
 * Date:2024-05-16 21:21
 * Description:工厂中,质检,5个工人检查,所有人都认为通过,才通过
 * History:
 * <author>    <time>    <version>    <desc>
 * 作者姓名     修改时间     版本号        描述
 */
public class CountDownLatchDemo1 {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(5);
        ExecutorService service = Executors.newFixedThreadPool(5);

        for (int i = 0; i < 5; i++) {
            final int no = i+1;
            Runnable r = new Runnable() {

                @Override
                public void run() {
                    try {
                        Thread.sleep((long) (Math.random() * 10000));
                        System.out.println("No." + no + "完成了检查");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        latch.countDown();
                    }
                }
            };
            service.submit(r);
        }
        System.out.println("等待5个人检查完....");
        // 当5个线程执行完 调用了latch.countDown count减到0了 才会走完await 否则一直阻塞在这里
        latch.await();
        System.out.println("所有人都完成了工作,进入下一个环节");
    }
}
